<template>
  <div class="searchBox">
    <teleport to=".header">
      <shopHeader @btnSearch="btnSearchHandler" @searchText="searchHandler" center="search" right="search"/>
    </teleport>

    <div class="search">

      <div class="hotsearch" v-if="!is_search && lastSearch.length">
        <div class="tit" >
          <p>最近搜索</p>
          <p class="hidden" @click="delHandler"><van-icon name="delete-o" /></p>
        </div>
        <ul>
          <li 
            v-for="item in lastSearch" 
            :key="item.wordid"
            @click="chickHandler(item)"
            >{{ item.keyword }}</li>
        </ul>
      </div>

      <div class="hotsearch" v-if="!is_search">
        <div class="tit">
          <p>热门搜索</p>
          <p class="hidden" @click="hiddenHandler">{{ is_hidden?'隐藏':'显示' }}</p>
        </div>
        <ul v-if="is_hidden">
          <li 
            v-for="item in hotList" 
            :key="item.wordid"
            @click="chickHandler(item)"
            >{{ item.keyword }}</li>
        </ul>
        <p v-else class="two">已隐藏搜索发现</p>
      </div>

      <div class="realsearch" v-if="is_search">
        <ul>
          <li 
            @click="chickHandler({'wordid':item.proid,'num':item.discount,'keyword': item.brand})" 
            v-for="item in searchList" 
            :key="item.proid">
            <p class="left">{{ item.brand }}</p>
            <p class="right">{{ item.category }}</p>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts" name="search">
import { useRouter } from 'vue-router'
const $myRouter = useRouter()
import shopHeader from "../../components/header.vue"
import { getHotSearch, getSearchLish } from '../../request/search.ts'
import { onMounted, ref} from "vue"

interface SearchData{
  wordid?: string
  num?: number
  keyword?: string
}

interface GoodsInfo {
  img1?: string
  proid?: string
  proname?: string
  originprice?: number
  discount?: number
  [key: string]: any
}

interface Response<T>{
  code?: string
  data?: Array<T>
}
const hotList = ref<Array<SearchData>>([])
const is_hidden = ref<boolean>(true)
const is_search = ref<boolean>(false)
const lastSearch = ref<Array<SearchData>>([])
const searchList = ref<Array<GoodsInfo>>([])
// 实时搜索
const searchHandler = async (value: string) => {
  if(!value.trim()){
    is_search.value = false
    searchList.value = []
    return
  }
  const res = await getSearchLish(value.trim())
  if((res as Response<GoodsInfo>).code !== '200') return
  searchList.value = res.data
  is_search.value = true
}
// 确定搜索按钮
const btnSearchHandler = (val: string) => {
  chickHandler({
    'wordid':Math.random().toString().slice(-8),
    'num':Math.floor(Math.random() * 999999 - 10000 + 1) - 10000,
    'keyword': val})
}
// 点击热门搜索隐藏
const hiddenHandler = () => {
  is_hidden.value = !is_hidden.value
}

// 搜索热门列表
const hotSearchHandler = async () => {
  const hotRes = await getHotSearch()
  if ((hotRes as Response<SearchData>).code !== '200') return
  
  hotRes.data.forEach((item: SearchData) => {
    item.keyword && hotList.value.push(item)
  })
}

// 最近搜索列表
const lastSearchHandler = () => {
  const res = JSON.parse(window.localStorage.getItem('lastSearch') || '[]') 
  lastSearch.value = res as SearchData[]
}

// 点击商品跳转
const chickHandler = (item: SearchData) => {
  const index = lastSearch.value.findIndex(key => {return key.keyword === item.keyword})
  if(index !== -1) {
    lastSearch.value.splice(index, 1)
  }
  lastSearch.value.unshift(item)
  window.localStorage.setItem('lastSearch',JSON.stringify(lastSearch.value))

  $myRouter.replace({path: '/list', query: {keyword: item.keyword}})
}

// 删除最近搜索
const delHandler = () => {
  window.localStorage.removeItem('lastSearch')
  lastSearch.value = []
}
onMounted(() => {
  hotSearchHandler()
  lastSearchHandler()
})
</script>
<style scoped lang="scss">
.realsearch{
  width: 100%;
  position: absolute;
  background-color: #fff;
  top: 50px;
  >ul{
    padding: 10px;
    box-sizing: border-box;
    >li{
      display: flex;
      justify-content: space-between;
      margin-bottom: 10px;
      >.right{
        background-color: #eff2f5;
        color: #686868;
        height: 25px;
        line-height: 25px;
        padding-left: 5px;
        padding-right: 5px;
      }
      >.left{
        height: 25px;
        line-height: 25px;
      }
    }
  }
}
.hotsearch{
  overflow: hidden;
  margin-bottom: 10px;
  padding:0 10px;
  box-sizing: border-box;
  p{
    font-size: 18px;
    margin-bottom: 15px;
  }
  ul{
    color: #686868;
    
    li{
      float: left;
      background-color: #eff2f5;
      box-sizing: border-box;
      margin-right: 10px;
      padding-left: 5px;
      padding-right: 5px;
      margin-bottom: 10px;
      height: 25px;
      line-height: 25px;
      font-size: 14px;
    }
  }
  .tit{
    clear: both;
    display: flex;
    justify-content:space-between;
    .hidden{
      color: darkgray;
    }
  }
  .two{
    display: inline-block;
    width: 100%;
    transform: translateY(50%);
    text-align: center;
    font-size: 16px;
  }
}
</style>
